package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.MemberPriceTo;
import com.atguigu.common.to.SkuFullReductionTo;
import com.atguigu.common.to.SkuLadderTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsMode;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeignService wareFeignService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuSaveVo(SpuSaveVo spuSaveVo) {
        // 保存spu基本信息 pms_spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuSaveVo, spuInfoEntity);
/*        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());*/
        // 成功保存会返回生成的主键id
        this.save(spuInfoEntity);

        // 保存spu的规格参数 pms_product_attr_value
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(item -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(item.getAttrId());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setAttrName(attrService.getById(item.getAttrId()).getAttrName());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(productAttrValueEntities);

        // 保存spu描述信息 pms_spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = spuSaveVo.getDecript();
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.save(spuInfoDescEntity);

        // 保存spu 图片信息 pms_sku_images
        List<String> images = spuSaveVo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        // 保存spu的sku基本信息 pms_sku_info
        List<Skus> skus = spuSaveVo.getSkus();
        for (Skus sku : skus) {
            SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
            skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
            skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
            skuInfoEntity.setSpuId(spuInfoEntity.getId());
            skuInfoEntity.setSaleCount(0L);
            BeanUtils.copyProperties(sku, skuInfoEntity);
            skuInfoService.save(skuInfoEntity);

            // 保存spu的sku的图片信息 pms_sku_images
            List<Images> imagesList = sku.getImages();
            List<SkuImagesEntity> skuImagesEntities = imagesList.stream().map((image) -> {
                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                BeanUtils.copyProperties(image, skuImagesEntity);
                return skuImagesEntity;
            }).filter(image -> {
                return !StringUtils.isEmpty(image.getImgUrl());
            }).collect(Collectors.toList());
            skuImagesService.saveBatch(skuImagesEntities);

            // 保存spu的sku的销售属性以及价格 pms_sku_sale_attr_value
            List<Attr> attr = sku.getAttr();
            List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(item -> {
                SkuSaleAttrValueEntity valueEntity = new SkuSaleAttrValueEntity();
                BeanUtils.copyProperties(item, valueEntity);
                valueEntity.setSkuId(skuInfoEntity.getSkuId());
                return valueEntity;
            }).collect(Collectors.toList());
            skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

            // 调用远程服务
            //  1. 保存打折 sms_sku_ladder
            SkuLadderTo skuLadderTo = new SkuLadderTo();
            skuLadderTo.setSkuId(skuInfoEntity.getSkuId());
            BeanUtils.copyProperties(sku, skuLadderTo);
            couponFeignService.saveSkuLadder(skuLadderTo);

            //  2. 保存满减 sms_sku_full_reduction
            SkuFullReductionTo fullReductionTo = new SkuFullReductionTo();
            fullReductionTo.setSkuId(skuInfoEntity.getSkuId());
            BeanUtils.copyProperties(sku, fullReductionTo);
            couponFeignService.saveSkuFullReduction(fullReductionTo);

            //  3. 保存会员价 sms_member_price
            List<MemberPrice> memberPriceList = sku.getMemberPrice();
            List<MemberPriceTo> memberPriceTos = memberPriceList.stream().map(memberPrice -> {
                MemberPriceTo memberPriceTo = new MemberPriceTo();
                memberPriceTo.setSkuId(skuInfoEntity.getSkuId());
                memberPriceTo.setMemberPrice(memberPrice.getPrice());
                memberPriceTo.setMemberLevelName(memberPrice.getName());
                memberPriceTo.setMemberLevelId(memberPrice.getId());
                return memberPriceTo;
            }).collect(Collectors.toList());
            couponFeignService.saveBatchMemberPrice(memberPriceTos);
        }

        //  4. 保存成长值和金币 sms_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        Bounds bounds = spuSaveVo.getBounds();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        couponFeignService.saveSpuBounds(spuBoundTo);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();
        String status = (String) params.get("status");
        String key = (String) params.get("key");
        Long brandId = Long.parseLong(StringUtils.isEmpty((String) params.get("brandId")) ? "0" : (String) params.get("brandId"));
        Long catelogId = Long.parseLong(StringUtils.isEmpty((String) params.get("catelogId")) ? "0" : (String) params.get("catelogId"));
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq("publish_status", status);
        }
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.like("spu_name", key).or()
                        .like("spu_description", key).or().eq("id", key);
            });
        }
        if (brandId > 0) {
            wrapper.eq("brand_id", brandId);
        }
        if (catelogId > 0) {
            wrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void upWares(Long spuId) {
        List<SkuEsMode> upProducts = new ArrayList<>();
        // 查询可检索属性
        List<ProductAttrValueEntity> attrForSpu = attrService.baseListForSpu(spuId);
        List<Long> attrIds = attrForSpu.stream()
                .map(ProductAttrValueEntity::getAttrId)
                .collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.getAttrSearchByAttrIds(attrIds);
        // 封装attrs

        List<SkuEsMode.Attrs> attrs = attrForSpu.stream()
                .filter(item -> searchAttrIds.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsMode.Attrs attr = new SkuEsMode.Attrs();
                    BeanUtils.copyProperties(item, attr);
                    return attr;
                })
                .collect(Collectors.toList());
        // 组装数据
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSkusBySpuId(spuId);
        List<SkuEsMode> skuEsModes = new ArrayList<>();
        for (SkuInfoEntity skuInfoEntity : skuInfoEntityList) {
            SkuEsMode skuEsMode = new SkuEsMode();
            // 复制共同选项
            BeanUtils.copyProperties(skuInfoEntity, skuEsMode);
            skuEsMode.setSkuPrice(skuInfoEntity.getPrice());
            skuEsMode.setSkuImg(skuInfoEntity.getSkuDefaultImg());
            // 调用库存服务查询是否有库存
            R skuStock = wareFeignService.getSkuStock(skuInfoEntity.getSkuId());
            Integer stock = (Integer) skuStock.get("stock");
            skuEsMode.setHasStock(stock != null && stock > 0);
            // 设置商品热度
            skuEsMode.setHostScore(0L);
            // 查询商标名和图片
            BrandEntity brand = brandService.getById(skuEsMode.getBrandId());
            skuEsMode.setBrandName(brand.getName());
            skuEsMode.setBrandImg(brand.getLogo());
            // 查询分类名
            CategoryEntity category = categoryService.getById(skuEsMode.getCatalogId());
            skuEsMode.setCatalogName(category.getName());
            // 设置查询属性
            skuEsMode.setAttrs(attrs);
            // 添加进数组
            skuEsModes.add(skuEsMode);
        }

        // 放入 ES
        searchFeignService.productStatusUp(skuEsModes);

        // 更新状态
        this.update(new UpdateWrapper<SpuInfoEntity>()
                .eq("id", spuId)
                .set("publish_status", ProductConstant.PUBLISH_STATUS.UP_PRODUCT.getCode()));
    }

}